package com.wHitE.dao.impl;

import com.wHitE.dao.AddBookDao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class AddBookDaoImpl implements AddBookDao {
    private String msg;

    @Override
    public String addBook(String name, double price, int quantity, String coverImg, String author, String uploader) {
        try {
            // 连接（JDBC）数据库并将数据新增到数据库（MySQL）中
            // 1.加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.连接数据库
            Connection connection = DriverManager.getConnection("jdbc:mysql:" +
                    "//localhost:3306/javaweb_database", "root", "123456");
            // 新增
            // 发送SQL语句
            // 执行
            String sql = "insert into book (name,price,quantity ,coverImg,author,uploader) values (?,?,?,?,?,?)";
            PreparedStatement pst = connection.prepareStatement(sql);
            pst.setString(1, name);
            pst.setDouble(2, price);
            pst.setInt(3, quantity);
            pst.setString(4, coverImg);
            pst.setString(5, author);
            pst.setString(6, uploader);
            msg = "新增失败,发生错误";
            if (pst.executeUpdate() > 0) {
                msg = "success";
            }
            // 关闭执行
            pst.close();
            // 断开连接
            connection.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return msg;
    }
}
